import App from './App'
import CryptoJS from '@/utils/crypto-js.js'

// #ifndef VUE3
import Vue from 'vue'
import './uni.promisify.adaptor'
require('common/function.js')
import uView from '@/uni_modules/uview-ui'
Vue.use(uView)

import loading from 'components/loading.vue';
import navtop from 'components/navtop.vue';
Vue.component('loading', loading)
Vue.component('navtop', navtop)
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
  ...App
})
// 引入请求封装
require('./utils/request/index')(app)
import addInterceptor from '@/common/addInterceptor.js'
Vue.use(addInterceptor, app)
app.$mount()
// #endif

// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
  const app = createSSRApp(App)
  return {
    app
  }
}
// #endif

// #ifdef H5
const get_crypt = function(string){
	var keyStr = CryptoJS.MD5(timestamp + 'cscms_saas_theatre').toString();
	var ivstr = keyStr.substr(0,8);
	var ivHex = CryptoJS.enc.Utf8.parse(ivstr);
	var keyHex = CryptoJS.enc.Utf8.parse(keyStr);
	var decrypted = CryptoJS.DES.decrypt({
		ciphertext: CryptoJS.enc.Hex.parse(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(string)))
	}, keyHex, {
		iv: ivHex,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7
	});
	return decrypted.toString(CryptoJS.enc.Utf8);
}
if(apiurl) app.globalData.apiurl = get_crypt(apiurl);
if(apikey) app.globalData.apikey = get_crypt(apikey);
if(appid) app.globalData.appid = appid;
if(siteid) app.globalData.siteid = siteid;
// if(user_token) uni.setStorageSync('user_token',user_token);
// #endif
const sync = uni.getSystemInfoSync();
//默认数据
const get_post = function(obj,callback){
	// #ifdef APP-PLUS
	if(app.globalData.idfa == ''){
		if(sync.platform == 'ios'){
			plus.device.getInfo({//需要勾选IDFA
				success:function(e){
					if(e.idfa) app.globalData.idfa = e.idfa;
				}
			});
		}else{
			plus.device.getOAID({
				success:function(e){
					if(e.oaid) app.globalData.idfa = e.oaid;
				}
			});
		}
	}
	// #endif
	obj.platform = sync.platform;
	obj.brand = sync.deviceBrand;
	obj.version = sync.appWgtVersion;
	obj.deviceid = CryptoJS.MD5(sync.deviceId).toString();
	obj.timestamp = Date.parse(new Date())/1000;
	obj.user_token = uni.getStorageSync('user_token');
	obj.lnvite_code = uni.getStorageSync('lnvite_code');
	obj.client_id = app.globalData.client_id;
	obj.siteid = app.globalData.siteid;
	obj.idfa = app.globalData.idfa;
	obj.openid = app.globalData.openid;
	if(!obj.brand) obj.brand = 'other';
	// #ifdef H5
	obj.platform = 'mp';
	// #endif
	// #ifdef MP-WEIXIN
	obj.platform = 'applet';
	// #endif
	return get_sign(obj,callback);
}
//数据签名
const get_sign = function(obj,callback){
	//生成key升序数组
	var arr = Object.keys(obj),str = '';
	arr.sort();
	var k = 0;
	for(var i in arr){
		if(obj[arr[i]] != undefined && obj[arr[i]] != null && obj[arr[i]] !== '' && arr[i] != 'sign'){
			if(k == 0){
				str += arr[i] +'='+ obj[arr[i]];
			}else{
				str += '&'+arr[i] +'='+ obj[arr[i]];
			}
			k++;
		}else{
			delete obj[arr[i]];
		}
	}
	var encrypted = CryptoJS.MD5(str + app.globalData.apikey).toString().toUpperCase();
	obj.sign = encrypted;
	typeof callback == "function" && callback(obj);
	if(callback == 'uri'){
		str += '&sign='+encrypted;
		return str;
	}
	return obj;
}
//网络请求
const get_curl = function(path,data,callback){
	let post = get_post(data);
	//网络请求
	uni.request({
		url: app.globalData.apiurl+path,
		data: post,
		header: {
			'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' // 默认值
		},
		method: 'POST',
		success: res => {
			if(res.statusCode && res.statusCode != 200) { //api错误
				uni.showToast({
					title: 'api接口异常',
					icon:'none'
				});
				return;
			}
			if(res.data.code == undefined){ //返回状态码code判断:1成功,0错误,-1未登录
				uni.showToast({
					title: 'api接口异常',
					icon:'none'
				});
			} else{
				if(res.data.code == -1) {
					uni.removeStorageSync('user_token');
					uni.navigateTo({
						url: './user/login',
						fail: function(e){
							console.log(e);
						}
					});
				}
				if(res.data.code == 0) {//code为1失败，code为0成功
					uni.showToast({
						title: res.data.msg,
						icon:'none'
					});
				}
			}
			typeof callback == "function" && callback(res.data);
		},
		fail: (e) => {
			console.log(e);
			uni.showToast({
				title: '网络异常',
				icon: 'none'
			});
			typeof callback == "function" && callback({code: -9});
		}
	});
}
//上传文件，支持多文件
const get_upfiles = (path,files,post,callback,progress) =>{
	const uploadTask = uni.uploadFile({
		url: app.globalData.apiurl+path,
		// #ifdef MP-WEIXIN
		filePath: files[0].uri,
		name: files[0].name,
		// #endif
		// #ifndef MP-WEIXIN
		files: files,
		// #endif
		formData: get_post(post),
		success: (res) => {
			res.data = JSON.parse(res.data);
			if(res.data.code != undefined){
				if(res.data.code == -1){
					uni.removeStorageSync('user_token');
					uni.navigateTo({
						url: '/pages/user/login',
						fail: function(e){
							console.log(e);
						}
					});
					return;
				}else if(res.data.code == 0){
					uni.showToast({
						title: res.data.msg,
						icon: 'none'
					});
				}
			}else{
				console.log(res);
				uni.showToast({
					title:"无状态码",
					icon:'none'
				});
				return;
			}
			typeof callback == "function" && callback(res.data);
		},
		fail:(e) => {
			uni.hideLoading();
			uni.showToast({
				title: '上传失败',
				icon: 'none'
			});
		}
	});
	uploadTask.onProgressUpdate((res) => {
		typeof progress == "function" && progress(res.progress);
	});
}
//获取小程序code
const get_applet_code = function(callback){
	// #ifdef MP-WEIXIN
	uni.login({
		provider: 'weixin',
		success: function (res) {
			typeof callback == "function" && callback(res.code);
		},
		fail: function(e){
			typeof callback == "function" && callback('');
		}
	});
	// #endif
	// #ifndef MP-WEIXIN
	typeof callback == "function" && callback('');
	// #endif
}
//请求支付
const get_pay = function(type,row,callback){
	if(row.payurl != undefined){
		//H5支付
		uni.navigateTo({
			url: '/pages/web/index?url='+row.payurl,
			fail: function(e){
				console.log(e);
			}
		});
	}else{
		// #ifndef H5
		get_app_pay(type,row.payinfo,callback);
		// #endif
		// #ifdef H5
		get_wxmp_pay(row.payinfo,callback);
		// #endif
	}
}
//APP、小程序支付
const get_app_pay = function(type,row,callback){
	uni.requestPayment({
		provider: type,
		// #ifdef MP-WEIXIN
		appId: row.appId, //小程序Appid
		timeStamp: row.timeStamp, //创建订单时间戳
		nonceStr: row.nonceStr,
		package: row.package, // 订单包
		signType: 'MD5', // 加密方式统一'MD5'
		paySign: row.paySign, // 后台支付签名返回
		// #endif
		// #ifdef APP-PLUS
		orderInfo: row,
		// #endif
		success() {
			typeof callback == "function" && callback('ok');
		},
		fail(e) {
			uni.showToast({title:'订单支付失败~',icon:'none'});
			console.log('fail:' + JSON.stringify(e));
		}
	})
}
//微信公众号支付
const get_wxmp_pay = function(row,callback){
	if(typeof WeixinJSBridge == "undefined"){
		if(document.addEventListener ){
			document.addEventListener('WeixinJSBridgeReady',function(){
				WeixinJSBridge.invoke('getBrandWCPayRequest',row,function(res){
					if(res.err_msg === 'get_brand_wcpay_request:ok') {
						typeof callback == "function" && callback('ok');
					}else{
						uni.showToast({title:'订单支付失败~',icon:'none'});
					}
				});
			},false);
		}else if(document.attachEvent){
			document.attachEvent('WeixinJSBridgeReady',function(){
				WeixinJSBridge.invoke('getBrandWCPayRequest',row,function(res){
					if(res.err_msg === 'get_brand_wcpay_request:ok') {
						typeof callback == "function" && callback('ok');
					}else{
						uni.showToast({title:'订单支付失败~',icon:'none'});
					}
				});
			}); 
			document.attachEvent('onWeixinJSBridgeReady',function(){
				WeixinJSBridge.invoke('getBrandWCPayRequest',row,function(res){
					if(res.err_msg === 'get_brand_wcpay_request:ok') {
						typeof callback == "function" && callback('ok');
					}else{
						uni.showToast({title:'订单支付失败~',icon:'none'});
					}
				});
			});
		}
	}else{
		WeixinJSBridge.invoke('getBrandWCPayRequest',row,function(res){
			if(res.err_msg === 'get_brand_wcpay_request:ok') {
				typeof callback == "function" && callback('ok');
			}else{
				uni.showToast({title:'订单支付失败~',icon:'none'});
			}
		});
	}
}
Vue.prototype.http = {
    get_curl,
	get_upfiles,
	get_applet_code,
	get_pay
};